package personal.leil.learning.utils;

import personal.leil.learning.DNode;
import personal.leil.learning.SNode;

import java.util.Objects;

/**
 * 链表工具类
 *
 * @author Leil
 * @version 1.0
 * @since 2024-1-15
 */
public class LinkedListUtils {

    public static void printSingleLinkedList(SNode head) {
        StringBuilder sb = new StringBuilder();
        sb.append(head.getData());
        SNode current = head;
        while (current.getNext() != null) {
            SNode next = current.getNext();
            sb.append("=>");
            sb.append(next.getData());
            current = next;
        }
        System.out.println(sb);
    }

    public static void printDoubleLinkedList(DNode head) {
        StringBuilder sb = new StringBuilder();
        sb.append(head.getData());
        DNode current = head;
        while (current.getNext() != null) {
            DNode next = current.getNext();
            DNode current1 = next.getPrev();
            if (Objects.equals(current, current1)) {
                sb.append("<=>");
            }
            sb.append(next.getData());
            current = next;
        }
        System.out.println(sb);
    }


    /**
     * 基于数组生成一个单链表
     * @param arr   source array
     * @return      head for linked list
     */
    public static SNode buildSingleLinkedList(int[] arr) {
        if (arr.length < 2) {
            return null;
        }
        SNode head = new SNode(arr[0]);
        SNode current = head;
        for (int i = 1; i < arr.length; i++) {
            current = current.setNext(new SNode(arr[i]));
        }
        return head;
    }


}
